<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="82px">
      <el-form-item label="所属学校ID" prop="schoolId">
        <el-input
          v-model="queryParams.schoolId"
          placeholder="请输入所属学校ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属班级" prop="classId">
        <el-select
            v-model="queryParams.classId"
            placeholder="请选择班级"
            clearable
            style="width: 150px"
            @change="handleQuery"
        >
        <el-option
            v-for="cls in uniqueClasses"
        :key="cls.classId"
        :label="cls.className"
        :value="cls.classId"
        />
        </el-select>
      </el-form-item>
      <el-form-item label="学号" prop="studentCode">
        <el-input
          v-model="queryParams.studentCode"
          placeholder="请输入学号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="学生姓名" prop="fullName">
        <el-input
          v-model="queryParams.fullName"
          placeholder="请输入学生姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="性别">
        <el-select v-model="queryParams.gender" placeholder="请选择性别" clearable style="width: 120px">
          <el-option label="男" value="male" />
          <el-option label="女" value="female" />
        </el-select>
      </el-form-item>
      <el-form-item label="入学日期" prop="enrollmentDate">
        <el-date-picker clearable
          v-model="queryParams.enrollmentDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择入学日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['schoolmanage:students:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['schoolmanage:students:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['schoolmanage:students:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['schoolmanage:students:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="info"
            plain
            icon="Upload"
            @click="handleImport(useExampleStore().school)"
            v-hasPermi="['schoolmanage:students:import']"
        >导入</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="studentsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="学生ID" align="center" prop="studentId" />
      <el-table-column label="所属学校ID" align="center" prop="schoolId" />
      <el-table-column label="班级名称" align="center" prop="className">
        <template #default="scope">
          {{ scope.row.className }}
        </template>
      </el-table-column>
      <el-table-column label="学号" align="center" prop="studentCode" />
      <el-table-column label="学生姓名" align="center" prop="fullName" />
      <el-table-column label="性别" align="center" prop="gender">
        <template #default="scope">
          {{ scope.row.gender === 'male' ? '男' : '女' }}
        </template>
      </el-table-column>
      <el-table-column label="入学日期" align="center" prop="enrollmentDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.enrollmentDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['schoolmanage:students:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['schoolmanage:students:remove']">删除</el-button>
<!--          <el-button link type="danger" icon="MessageBox" @click="handleGoToExam(scope.row)">配置考试信息</el-button>-->
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改学生信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="studentsRef" :model="form" :rules="rules" label-width="95px">
        <el-form-item label="所属学校ID" prop="schoolId">
          <el-input v-model="form.schoolId" placeholder="请输入所属学校ID" disabled/>
        </el-form-item>
        <el-form-item label="所属班级">
          <!-- 班级下拉框 -->
          <el-select
              v-model="form.classId"
              placeholder="请选择班级"
              clearable
          >
            <el-option
                v-for="cls in uniqueClasses"
                :key="cls.classId"
                :label="cls.className"
                :value="cls.classId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="学号" prop="studentCode">
          <el-input v-model="form.studentCode" placeholder="请输入学号" />
        </el-form-item>
        <el-form-item label="学生姓名" prop="fullName">
          <el-input v-model="form.fullName" placeholder="请输入学生姓名" />
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="form.gender" placeholder="请选择性别">
            <el-option label="男" value="male" />
            <el-option label="女" value="female" />
          </el-select>
        </el-form-item>
        <el-form-item label="入学日期" prop="enrollmentDate">
          <el-date-picker clearable
            v-model="form.enrollmentDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择入学日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 导入文件对话框 -->
    <el-dialog :title="'导入学生信息'" v-model="importDialogVisible" width="300px">
      <template #default>
        <el-upload
            ref="uploadRef"
            action="#"
            :show-file-list="false"
            :before-upload="beforeUpload"
        >
          <el-button type="primary">选择文件</el-button>
        </el-upload>
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="importDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitImport">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 考试信息对话框 -->
    <!-- 考试信息对话框 -->
    <el-dialog title="考试信息" v-model="examDialogVisible" width="400px">
      <el-form label-width="120px">
        <!-- 表单内容保持不变 -->
        <el-form-item label="原始学号">
          <el-input v-model="examInfo.originalStudentCode" disabled />
        </el-form-item>
        <el-form-item label="考试学号">
          <el-input v-model="examInfo.studentCode" disabled />
        </el-form-item>
        <el-form-item label="考试编号">
          <el-input v-model="examInfo.examNumber" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="saveExamInfo">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Students">
import { ref } from 'vue';
import {
  listStudents,
  getStudents,
  deleteStudent,
  addStudents,
  updateStudents,
  importStudents,
  checkStudentAssociations,
} from "@/api/schoolmanage/students"
import {listClasses} from "@/api/schoolmanage/classes.js";
import {useExampleStore} from "@/stores/exampleStore.js";
import {ElMessage, ElMessageBox} from "element-plus";
import {parseTime} from "../../../utils/ruoyi.js";
import { useRouter } from 'vue-router'
const router = useRouter()

const { proxy } = getCurrentInstance()

const studentsList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const classesList = ref([])

// 添加考试对话框相关状态
const examDialogVisible = ref(false);
const examInfo = reactive({
  studentCode: '',
  examNumber: '',
  originalStudentCode: ''
});
// 保存考试信息到远程接口（示例）
const saveExamInfo = () => {
  // 构造 StudentInfoDTO 数据（匹配后端接收类）
  const examData = {
    studentId: examInfo.originalStudentCode, // 原始学号
    examNumber: examInfo.examNumber,         // 考试编号
    fullName: studentsList.value.find(s => s.studentCode === examInfo.originalStudentCode)?.fullName || '', // 学生姓名
    // 其他字段按需补充（如考场号、机器编号等）
  };
  // 调用远程接口（假设接口为保存考试信息）
  return saveStudentExamInfo(examData); // 需在 api 中定义该接口
};

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    schoolId: useExampleStore().school,
    classId: null,
    studentCode: null,
    fullName: null,
    gender: null,
    enrollmentDate: null,
  },
  rules: {
    schoolId: [
      { required: true, message: "所属学校ID不能为空", trigger: "blur" }
    ],
    classId: [
      { required: true, message: "所属班级ID不能为空", trigger: "blur" }
    ],
    studentCode: [
      { required: true, message: "学号不能为空", trigger: "blur" }
    ],
    fullName: [
      { required: true, message: "学生姓名不能为空", trigger: "blur" }
    ],
    createTime: [
      { required: true, message: "创建时间不能为空", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)
// 新增：导入对话框可见性
const importDialogVisible = ref(false);
// 新增：上传文件引用
const uploadRef = ref(null);
// 新增：上传的文件
const uploadFile = ref(null);

/** 查询学生信息列表 */
function getList() {
  loading.value = true
  queryParams.value.schoolId = useExampleStore().school
  listStudents(queryParams.value).then(response => {
    console.log("xxxxxx....."+queryParams.value.schoolId)
    studentsList.value = response.rows.map(students => {
      // 直接从 students.classes 取班级名称
      const className = students.classes?.className || '未分配班级'
      return {
        ...students,
        className // 覆盖或新增 className 字段
      }
    })
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    studentId: null,
    schoolId: useExampleStore().school,
    classId: null,
    studentCode: null,
    fullName: null,
    gender: null,
    enrollmentDate: null,
    createTime: null
  }
  proxy.resetForm("studentsRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.studentId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加学生信息"
  console.log(form.value)
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _studentId = row.studentId || ids.value
  getStudents(_studentId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改学生信息"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["studentsRef"].validate(valid => {
    if (valid) {
      if (form.value.studentId != null) {
        updateStudents(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addStudents(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
// 确保删除按钮绑定正确事件

// 方法实现
const handleDelete = async (row) => {
  try {
    // 第一步：基础确认
    await ElMessageBox.confirm('确定删除该学生吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // 第二步：检查关联记录（仅检查，不删除）
    const { data } = await checkStudentAssociations(row.studentId)

    // 第三步：根据检查结果处理
    if (data?.hasRecords) {
      await ElMessageBox.confirm(
          `该学生存在 ${data.count} 条关联记录，确认继续删除？`,
          '警告',
          {
            confirmButtonText: '确认删除',
            cancelButtonText: '取消',
            type: 'warning'
          }
      )
    }

    // 第四步：执行删除（不传force参数）
    await deleteStudent(row.studentId)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除失败')
    }
  }
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download('schoolmanage/students/export', {
    ...queryParams.value
  }, `students_${new Date().getTime()}.xlsx`)
}
const importId = ref(null);
// 新增：导入按钮操作
// 修正后代码
function handleImport(schoolId) { // 接收传入的学校ID
  importId.value = schoolId; // 正确赋值
  importDialogVisible.value = true;
}

// 新增：上传前处理
function beforeUpload(file) {
  uploadFile.value = file;
  return false; // 阻止默认上传行为
}

// 新增：提交导入
function submitImport() {
  if (!uploadFile.value) {
    proxy.$modal.msgWarning("请选择要上传的文件");
    return;
  }
  const formData = new FormData();
  formData.append('file', uploadFile.value);
  if (importId.value) {
    formData.append('id', importId.value); // 添加 id 到 FormData
  }
  // 手动打印请求路径
  // 临时打印环境变量检查
  console.log('当前BASE_API:', import.meta.env.VITE_APP_BASE_API)
  importStudents(formData).then(response => {
    console.log('最终请求URL:',
        `${import.meta.env.VITE_APP_BASE_API}/schoolmanage/students/importData`
    )
    if (response.code === 200) {
      debugger
      proxy.$modal.msgSuccess("导入成功");
      importDialogVisible.value = false;
      getList();
    } else {
      debugger
      proxy.$modal.msgError("导入失败：" + response.msg);
    }
  }).catch(error => {
    debugger
    proxy.$modal.msgError("导入失败：" + error.message);
  });
}

// 1. 定义去重后的班级列表
const uniqueClasses = ref([]);

// 2. 获取班级列表并去重（建议在onMounted中调用）
onMounted(() => {
  getClassesList();  // 加载班级列表
  getList()
});

// 3. 获取班级列表并处理去重
function getClassesList() {
  listClasses().then(response => {
    // 原始班级列表
    const originClasses = response.rows || [];
    // 按className去重（保留第一个出现的classId）
    const classMap = new Map();
    originClasses.forEach(cls => {
      if (!classMap.has(cls.className)) {
        classMap.set(cls.className, cls);
      }
    });
    // 转换为数组
    uniqueClasses.value = Array.from(classMap.values());
  });
}
</script>
